package org.feng.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

/**
 * BeanFactoryAware 实现类：可以获取到 BeanFactory 实例
 *
 * @version V1.0
 * @author: fengjinsong
 * @date: 2022年06月29日 14时03分
 */
@Component
@Slf4j
public class BeanFactoryAwareImpl implements BeanFactoryAware {

    private static BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        log.info("使用 BeanFactoryAware 获取到 BeanFactory {}", beanFactory);
        BeanFactoryAwareImpl.beanFactory = beanFactory;
    }

    public static <T> T getBean(Class<T> clazz) {
        return beanFactory.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return beanFactory.getBean(name, clazz);
    }

    public static Object getBusinessBean(BusinessOneEnum one, BusinessTwoEnum two) {
        String suffix = "BeanBusiness";
        String beanName = String.join("_", one.getName(), two.getName(), suffix);
        return getBean(beanName);
    }

    public static Object getBean(String name) {
        return beanFactory.getBean(name);
    }
}
